import React from 'react';
import { RouteLayout, ListPage, Form, ListViewPage } from 'weaver-mobile-page';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Modal, Popover, Icon, List, SearchBar, Checkbox, Tools, Bubble, Result, ActivityIndicator} from 'weaver-mobile';

const Item = Popover.Item;
const ButtonGroup = RouteLayout.ButtonGroup;
const AgreeItem = Checkbox.AgreeItem;
const getLabel = Tools.getLabel;
const template = {
    default: [
        {
            key: 'col1',
            configs: [
                {
                    key: 'col1_row1',
                    configs: [
                        {
                            key: 'name',
                            style: { fontWeight: "normal" }
                        },
                    ],
                },
                {
                    key: 'col1_row2',
                    configs: [
                        {
                            key: 'dataSpan',
                            className: "color-gray"
                        },
                        {
                            key: 'workflowrangespan',
                            className: "color-gray"
                        },
                    ],
                },
                {
                    key: 'col1_row3',
                    configs: [
                        {
                            key: 'uidSpan',
                            className: "color-gray"
                        },
                        {
                            key: 'agenteridspan',
                            className: "color-gray"
                        },
                    ],
                },
            ],
        },
    ],
};
@inject("wfAgentStore")
@inject("wfSearchPageStore")
@observer
export default class TemManagement extends React.Component {
    componentWillMount() {
        const { location = {} } = this.props;
        const { pathname = "" } = location;
        const { searchTemplate, agentTemplateList, getPageTitle, setInitDatas, agentTemplateCondition, setTempMDatas, setMobxStore,tempManagement } = this.props.wfAgentStore;
        const { searchParams } = tempManagement;
        getPageTitle(pathname);

        // setMobxStore({
        //     layout: new RouteLayout.Store({ route: "/agent/temManagement", id: "advanceSearch" }),
        //     searchPage_layout: new RouteLayout.Store({ route: "/agent/temManagement", id: "searchPage" }),
        //     searchValue: "",
        // })
        setInitDatas({ nowPath: pathname })
        // // if (JSON.stringify(toJS(searchParams)) !== "{}") {
        // //     agentTemplateList(searchParams);
        // // } else {
            // agentTemplateList();
        // // }
        searchTemplate();
        agentTemplateCondition();
        setTempMDatas({ propsVisiable: false, isShowCheck: false })

    }

    componentWillUpdate() {
        const { location, wfAgentStore } = this.props;
        const { getPageTitle } = wfAgentStore;
        const { pathname = "" } = location;
        getPageTitle(pathname);
    }

    getGroupButton = () => {
        const { tempManagement } = this.props.wfAgentStore;
        const { isSelectedAll } = tempManagement;
        return (
            <div className="wf-agent-importFromTemp-button-group" >
                <ButtonGroup
                    data={[
                        {
                            key: 'selectAll',
                            text: <AgreeItem checked={isSelectedAll}>  {getLabel(556,"全选")}</AgreeItem>,
                            onClick: () => {
                                const { setTempMDatas, tempManagement } = this.props.wfAgentStore;
                                const { selectedRowKeys, listViewPage_listsotre } = tempManagement;
                                let arr = [];
                                let datas = toJS(listViewPage_listsotre.data);
                                datas.map(item => { arr.push(item.randomFieldId); return arr; });
                                if (toJS(selectedRowKeys).length === arr.length) {
                                    setTempMDatas({ selectedRowKeys: [], isSelectedAll: false })
                                    listViewPage_listsotre.selectedRowKeys = []
                                } else {
                                    setTempMDatas({ selectedRowKeys: arr, isSelectedAll: true })
                                    listViewPage_listsotre.selectedRowKeys = arr;
                                }
                            },
                            className: "selectAll-base"
                        },
                        {
                            key: 'submit',
                            text: getLabel(32136,"批量删除"),
                            onClick: () => { this.onDelete(); },
                            type: 'primary',
                        }
                    ]
                    }
                />
            </div>
        )
    }

    onSelectAgent_back = (item) => {
        const { tempManagement, setTempMDatas } = this.props.wfAgentStore;
        const { datas, isShowCheck, selectedRowKeys } = tempManagement;
        if (isShowCheck) {
            let newdatas2 = [];
            toJS(datas).map(item => {
                newdatas2.push(item.id);
                return newdatas2;
            })
            let arr = [...toJS(selectedRowKeys)];
            if (arr.includes(item.id)) {
                arr.splice(arr.indexOf(item.id), 1);
            } else {
                arr.push(item.id);
            }
            setTempMDatas({ selectedRowKeys: arr })
            if (arr.length === newdatas2.length) {
                setTempMDatas({ isSelectedAll: true })
            } else {
                setTempMDatas({ isSelectedAll: false })
            }
        }
    }
    onSelectAgent = (selectedRowKeys = []) => {
        const { tempManagement, setTempMDatas } = this.props.wfAgentStore;
        const { listViewPage_listsotre } = tempManagement;
        setTempMDatas({ selectedRowKeys: selectedRowKeys })
        if (listViewPage_listsotre.data.length === selectedRowKeys.length) {
            setTempMDatas({ isSelectedAll: true })
        } else {
            setTempMDatas({ isSelectedAll: false })
        }
    }

    getListDom_back = () => {
        const { tempManagement } = this.props.wfAgentStore;
        const { datas, isShowCheck, selectedRowKeys } = tempManagement;
        let newDatas = toJS(datas);
        const items = [];
        newDatas.map(item => {
            items.push(<ListPage.Item
                key={item.id}
                data={item}
                showCheck={isShowCheck}
                checked={toJS(selectedRowKeys).includes(item.id)}
                template={template}
                swipeActionProps={{
                    style: { backgroundColor: 'gray' },
                    autoClose: true,
                    right: [
                        {
                            text: getLabel(93,'编辑'),
                            className: "bianji",
                            onPress: () => { this.editTemplate(item) },
                        },
                        {
                            text: getLabel(126371,'删除'),
                            className: "shanchu",
                            onPress: () => {
                                this.onDelete(item);
                            },
                        },
                    ]
                }}
                withSwipeAction={!isShowCheck && true}
                onSelect={() => {
                    this.onSelectAgent(item)
                }}
                onClick={() => {
                    this.onSelectAgent(item)
                }}
            >
            </ListPage.Item>)
            return items;
        })
        if (items.length > 0) {
            return <div className="wf-agent-agentList wf-agent-templatemanagement-listpart" >
                <List > {items} </List>
            </div>;
        } else {
            return (
                <div style={{ width: "100%", height: "100%" }} className="wf-agent-NoData">
                    <Result
                        img={<Icon type="no-data" size="lg" />}
                        message={getLabel(83553, "暂无数据")}
                    />
                </div>
            )
        }
    }

    getNodata = () => {
        return (
            <div style={{ width: "100%", height: "100%" }} className="wf-agent-NoData">
                <Result
                    img={<Icon type="no-data" size="lg" />}
                    message={getLabel(83553, "暂无数据")}
                />
            </div>
        )
    }

    getTemplate = (template) => {
        const newTemp = {
            default: [{
                // ...template,
                key: 'col_1',
                render: (data) => {
                    const { name, workflowrangespan, agenteridspan } = data;
                    return (
                        <div>
                            <div style={{ display: "flex" }}>
                                <div style={{ flex: "10", wordBreak: "break-all", color: "#333333" }}>
                                    {name}
                                </div>
                            </div>
                            <div style={{ color: "#999999" }}>
                                {getLabel(391149, "代理路径")}：{workflowrangespan}
                            </div>
                            <div style={{ color: "#999999" }}>
                                {getLabel(17566, '代理人')}：{agenteridspan}
                            </div>
                        </div>
                    );
                },
            }],
        };
        return newTemp;
    }
    getRowProps = (rowData) => {
        const { isShowCheck } = this.props.wfAgentStore.tempManagement;
        if (isShowCheck) {
            return {
                withSwipeAction: false,
            }
        } else {
            return {
                withSwipeAction: true,
            }
        }
    }
    getListDom = () => {
        const { wfAgentStore } = this.props;
        const { tempManagement } = wfAgentStore;
        const { listViewPage_listsotre, isShowCheck } = tempManagement;
        // let template = this.getTemplate();
        if (listViewPage_listsotre.data.length>0) {
            return (
                <ListViewPage.Normal
                    className="wf-tempManagement-list-view-page"
                    style={{ height: isShowCheck ? "calc(100% - 135px)" : "100%" }}
                    showCheck={isShowCheck}
                    rowKey="randomFieldId"
                    store={listViewPage_listsotre}
                    withSwipeAction
                    swipeActionProps={{
                        style: { backgroundColor: 'gray' },
                        autoClose: true,
                        right: [
                            {
                                text: getLabel(93,'编辑'),
                                className: "bianji",
                                onPress: (item) => { this.editTemplate(item) },
                            },
                            {
                                text: getLabel(91,'删除'),
                                className: "shanchu",
                                onPress: (item) => {
                                    this.onDelete(item);
                                },
                            },
                        ]
                    }}
                    getRowProps={this.getRowProps}
                    getTemplate={this.getTemplate}
                    onRowSelect={(onSelectAgent) => {
                        this.onSelectAgent(onSelectAgent)
                    }}
                />
            );
        } else {
            this.getNodata();
        }
      
    }

    //编辑模板
    editTemplate = (item) => {
        const { setAddAgent } = this.props.wfAgentStore;
        setAddAgent({ symbol: "editTemplate", templateid: item.randomFieldId })
        this.props.history.push("/agent/addAgent")
    }

    //删除模板
    onDelete = (item) => {
        const { deleteTemplate, tempManagement } = this.props.wfAgentStore;
        const { listViewPage_listsotre, isShowCheck } = tempManagement;
        const { selectedRowKeys } = listViewPage_listsotre;
        let agentid = "";
        if (isShowCheck && selectedRowKeys.length <= 0) {
            Bubble.warning(getLabel(391150,'请选择需要删除的模板'), 2);
        } else {
            if (item) {
                agentid = item.id || item.randomFieldId;
            } else {
                agentid = toJS(selectedRowKeys).join(",");
            }
            Modal.alert(getLabel(15097,'确定要删除吗？'), "", [
                { text: getLabel(201, '取消'), onPress: () => console && console.log('cancel') },
                {
                    text: getLabel(826,'确定'), onPress: () => {
                        deleteTemplate({ ids: agentid });
                    }
                },
            ])
        }
    }

    render() {
        const { wfAgentStore } = this.props;
        const { tempManagement, setAddAgent, initDatas, setAdvancedItem, layout, advancedItem, searchPage_layout, searchValue } = wfAgentStore;
        const { propsVisiable, isShowCheck, isShowLoading, searchParams, listViewPage_listsotre } = tempManagement;
        const { isAdVancedHasData, nowPath } = initDatas;
        let popover = (
            <Popover
                overlayClassName="fortest"
                overlayStyle={{ color: 'currentColor' }}
                visible={propsVisiable}
                mask={1}
                overlay={[
                    (<Item key="1" value="add">{getLabel(28051,"新建模板")}</Item>),
                    (<Item key="2" value="delete" >{getLabel(32136,"批量删除")}</Item>),
                ]}
                align={{
                    overflow: { adjustY: 0, adjustX: 0 },
                    offset: [-10, 0],
                }}
                onVisibleChange={(visible) => {
                    const { setTempMDatas } = this.props.wfAgentStore;
                    setTempMDatas({ propsVisiable: visible })
                }}
                onSelect={(key) => {
                    const { setTempMDatas } = this.props.wfAgentStore;
                    if (key.key === "1") {
                        setAddAgent({ symbol: "addTemplate" })
                        this.props.history.push("/agent/addAgent")
                    } else if (key.key === "2") {
                        setTempMDatas({ isShowCheck: true, propsVisiable: false})
                    }
                }}
            >
                <div style={{
                    height: '100%',
                    padding: '0 15px 0 0',
                    marginRight: '-15px',
                    alignItems: 'center',
                    display: "inline"
                }}
                >
                    <Icon type="ellipsis" />
                </div>
            </Popover>

        )
        return (
            <div className="templateManagement">
                <div>
                    <SearchBar
                        className="search-select"
                        placeholder={getLabel(18510, "请输入模板名称")}
                        showExtraButton
                        value={searchValue}
                        extraButton={[
                            { key: 'advanced', show: <Icon key={isAdVancedHasData ? "filter-o-hot" : "filter-o"} type={isAdVancedHasData ? "filter-o-hot" : "filter-o"} className={isAdVancedHasData && "color-blue"} /> },
                            { key: 'drop', show: popover },
                        ]}
                        onExtraButtonClick={(key) => {
                            if (key === "advanced") {
                                let newForm = new Form.Store()
                                newForm.initForm(advancedItem.conditioninfo, nowPath + '/advanceSearch');
                                let newSearchParams = toJS(searchParams)
                                if (newSearchParams.workflowid) {
                                    newSearchParams.workflowid = { value: [{ id: newSearchParams.workflowid, name: newSearchParams.workflowidspan }] }
                                } else {
                                    newSearchParams.workflowid = { value: [] }
                                }
                                if (newSearchParams.agenterid) {
                                    newSearchParams.agenterid = { value: [{ id: newSearchParams.agenterid, name: newSearchParams.agenteridspan }] }
                                } else {
                                    newSearchParams.agenterid = { value: [] }
                                }
                                newForm.updateFields({ ...newSearchParams, name: { value: searchValue }, });
                                setAdvancedItem({ form: newForm, parentPath: "temManagement" });
                                this.props.history.push(layout.path)
                            }
                        }}
                        onFocus={() => {
                            const { setState } = this.props.wfSearchPageStore
                            const { searchValue } = this.props.wfAgentStore;
                            setState({ placeholder: getLabel(197,"搜索"), ssName: "temManagement", searchValue: searchValue })
                            this.props.history.push(searchPage_layout.path)
                        }}
                    />
                </div>
                <div style={{ height: "100%" }}>
                    {isShowCheck && <div className="wf-agent-list-selectedMsg" >
                        <span className="wf-agent-list-selectedMsg-cancel" onClick={() => {
                            const { setTempMDatas, tempManagement } = this.props.wfAgentStore;
                            const { listViewPage_listsotre, isShowCheck } = tempManagement;
                            listViewPage_listsotre.setState({selectedRowKeys:[]})
                            setTempMDatas({ isShowCheck: false,isSelectedAll:false })
                        }}>{getLabel(201, '取消')}</span>
                        <span>{getLabel(500274, "已选择")}{" " + listViewPage_listsotre.selectedRowKeys.length + " "}{getLabel(18256,"条")}</span>
                    </div>}
                    {this.getListDom()}
                    {isShowLoading && <ActivityIndicator
                        toast
                        text={getLabel(500408 , "加载中...")}
                        animating={isShowLoading}
                    />}
                    {isShowCheck && this.getGroupButton()}
                </div>
            </div>
        );
    }
}

